import React, {Component} from 'react';
import {Text, View, TouchableOpacity, AsyncStorage} from 'react-native';
import WebIM from './../utils/Lib/WebIM';
import CountEmitter from './../utils/event/CountEmitter';
import {GiftedChat, Send} from 'react-native-gifted-chat';
import FetchUtils from './../utils/FetchUtils';
import utils from './../utils/utils';

export default class ChatPage extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        headerTitle: navigation.state.params ? navigation.state.params.title : null,
        headerTitleStyle: {
            alignSelf: 'center'
        },
        headerRight: <TouchableOpacity/>
    });

    constructor(props) {
        super(props);
        this.state = {
            messages: null,
            toUser: null,
            userId: null,
            userAvatar: null,
        }
    }

    componentWillMount() {
        CountEmitter.addListener('ChatRefresh', () => {
            console.log("聊天监听");
            /*每次监听事件触发就更新最新的聊天记录（本地）*/
            AsyncStorage.getItem("userId").then((userId) => {
                AsyncStorage.getItem(userId + "_" + this.props.navigation.state.params.toUser.username + "_chatList").then((msg) => {
                    try {
                        this.setState({
                            messages: JSON.parse(msg),
                        });
                    } catch (e) {
                        console.log(e);
                    }

                });
            });
        });
    }

    componentWillUnmount() {
        CountEmitter.removeListener('ChatRefresh', () => {
        });
    }

    componentDidMount() {
        this.setState({
            toUser: this.props.navigation.state.params.toUser ? this.props.navigation.state.params.toUser : null,
        });
        /*动态改变title*/
        this.props.navigation.setParams({
            title: this.props.navigation.state.params.toUser.username,
        });
        /*把聊天记录放进来*/
        AsyncStorage.getItem("userId").then((userId) => {
            AsyncStorage.getItem(userId + "_" + this.props.navigation.state.params.toUser.username + "_chatList").then((msg) => {
                this.setState({
                    messages: JSON.parse(msg),
                });
                AsyncStorage.getItem("avatar").then((avatar) => {
                    this.setState({
                        userAvatar: avatar,
                    })
                })

            });
        });
    }

    /*环信发送消息*/
    sendHXPrivateText = (message) => {
        let id = WebIM.conn.getUniqueId();                 // 生成本地消息id
        let msg = new WebIM.message('txt', id);      // 创建文本消息
        msg.set({
            msg: message,                  // 消息内容
            to: this.props.navigation.state.params.toUser.username,                          // 接收消息对象（用户id）
            roomType: false,
            success: function (id, serverMsgId) {
            },
            fail: function (e) {
                console.log(e);
            }
        });
        msg.body.chatType = 'singleChat';
        WebIM.conn.send(msg.body);
    };

    /*聊天UI,发送信息*/
    onSend(messages = []) {
        console.log(this.state.messages);
        /*发送信息的时候添加聊天列表记录*/
        AsyncStorage.getItem("XToken").then((xToken) => {
            let param = {
                toUser: this.state.toUser,
            };
            FetchUtils.postWithParamHeader(utils.apiUrl + '/chat/list', param, xToken, (res) => {

            });
        });
        console.log(messages);
        this.sendHXPrivateText(messages[0].text);
        // this.setState((previousState) => ({
        //     messages: GiftedChat.append(previousState.messages, messages),
        // }));
        AsyncStorage.getItem("userId").then((userId) => {
            AsyncStorage.getItem(userId + "_" + this.props.navigation.state.params.toUser.username + "_chatList").then((msg) => {
                // console.log(msg)
                if (msg === null) {
                    AsyncStorage.setItem(userId + "_" + this.props.navigation.state.params.toUser.username + "_chatList", JSON.stringify(messages), (error) => {
                        if (error) {
                            console.log(error)
                        } else {
                            CountEmitter.emit("ChatRefresh")
                        }
                    });
                } else {
                    let jsonMsg = JSON.parse(msg);
                    let newMsg = messages.concat(jsonMsg);
                    console.log(newMsg);
                    AsyncStorage.setItem(userId + "_" + this.props.navigation.state.params.toUser.username + "_chatList", JSON.stringify(newMsg), (error) => {
                        console.log(error);
                        if (error) {
                            console.log(error)
                        } else {
                            CountEmitter.emit("ChatRefresh")
                        }
                    });
                }
            })
        });

    }

    /*聊天UI*/
    renderSend(props) {
        return (
            <Send
                {...props}
            >
                <View style={{paddingBottom: 10, paddingRight: 15}}>
                    <Text style={{fontSize: 18, color: '#000'}}>发送</Text>
                </View>
            </Send>
        );
    }

    render() {
        return (
            <GiftedChat
                placeholder="请输入"
                showUserAvatar={true}
                renderSend={this.renderSend}
                messages={this.state.messages}
                onSend={(messages) => this.onSend(messages)}
                user={{
                    _id: 1,
                    avatar: utils.qiniuUrl + this.state.userAvatar + utils.qiniu200Url,
                }}
            />
        );
    }

}